﻿#region

using System;
using System.Threading;

#endregion

namespace ZOIL.DataModel
{
    public static class ReaderWriterLockSlimExtensions
    {
        public static T UseReadLock<T>(this ReaderWriterLockSlim rwl, Func<T> func)
        {
            rwl.EnterReadLock();
            try
            {
                return func();
            }
            finally
            {
                rwl.ExitReadLock();
            }
        }

        public static void UseReadLock(this ReaderWriterLockSlim rwl, Action action)
        {
            rwl.EnterReadLock();
            try
            {
                action();
            }
            finally
            {
                rwl.ExitReadLock();
            }
        }

        public static T UseWriteLock<T>(this ReaderWriterLockSlim rwl, Func<T> func)
        {
            rwl.EnterWriteLock();
            try
            {
                return func();
            }
            finally
            {
                rwl.ExitWriteLock();
            }
        }

        public static void UseWriteLock(this ReaderWriterLockSlim rwl, Action action)
        {
            rwl.EnterWriteLock();
            try
            {
                action();
            }
            finally
            {
                rwl.ExitWriteLock();
            }
        }


        public static IDisposable ReadLock(this ReaderWriterLockSlim rwl)
        {
            return new DisposableCreator(rwl.EnterReadLock, rwl.ExitReadLock);
        }
        public static IDisposable WriteLock(this ReaderWriterLockSlim rwl)
        {
            return new DisposableCreator(rwl.EnterWriteLock, rwl.ExitWriteLock);
        }
    }
}